/*
 * Copyright 2015 泛泛o0之辈
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.jfast.framework.upload;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class UploadFileIterator implements Iterator<UploadFile> {

	private String charset;

	private byte[] boundarys;

	private InputStream input;

	private ByteArrayOutputStream output;

	private UploadFile currentField;

	private List<UploadFile> currentNextFields;

	public UploadFileIterator(InputStream input, String charset,
			byte[] boundarys) {
		this.input = input;
		this.charset = charset;
		this.boundarys = boundarys;
		this.output = new ByteArrayOutputStream();
	}

	public boolean hasNext() {

		currentField = null;

		if (currentNextFields != null && !currentNextFields.isEmpty()) {
			currentField = currentNextFields.remove(0);
			return true;
		}

		int r = -1;
		byte[] buff = new byte[4096];
		List<byte[]> fieldList = null;
		List<byte[]> fileList = null;

		try {
			while ((r = input.read(buff)) != -1) {
				output.write(buff, 0, r);

				fieldList = MultiRequestFieldAnalizer.findFile(boundarys, output);

				if (fieldList != null && !fieldList.isEmpty()) {
					fileList = MultiRequestFieldAnalizer.getFilesByteList(
							fieldList, charset);
					if (fileList != null && !fileList.isEmpty()) {
						break;
					}
				}
			}

			if (fileList == null || fileList.isEmpty()) {
				return false;
			}
			if (fileList.size() > 1) {
				currentNextFields = new ArrayList<UploadFile>(fileList.size());
			}

			UploadFile uploadFile = null;
			for (int i = 0; i < fileList.size(); i++) {
				uploadFile = MultiRequestFieldAnalizer.getUploadFile(
						fileList.get(i), charset);

				if (i == 0) {
					currentField = uploadFile;
				} else {
					currentNextFields.add(uploadFile);
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			return false;
		}

		return currentField == null ? false : true;
	}

	public UploadFile next() {
		return this.currentField;
	}

	public void remove() {
		throw new UnsupportedOperationException();
	}
}
